package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.PictureAndTextEditorView;
import com.wbao.dianniu.customView.SpanTextView;
import com.wbao.dianniu.data.KnowImageData;
import com.wbao.dianniu.data.KnowledgeData;
import com.wbao.dianniu.emojiUtils.DisplayUtils;
import com.wbao.dianniu.http.ErrorCode;
import com.wbao.dianniu.listener.IKnowGoodListener;
import com.wbao.dianniu.listener.IKnowledgeDelListener;
import com.wbao.dianniu.listener.IKnowledgeDetailListener;
import com.wbao.dianniu.listener.IScoreReduceListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.KnowDelManager;
import com.wbao.dianniu.manager.KnowDetailManager;
import com.wbao.dianniu.manager.KnowGoodManager;
import com.wbao.dianniu.update.KnowledgeHelper;
import com.wbao.dianniu.manager.ScoreReduceManager;
import com.wbao.dianniu.update.ScoreChangeManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.utils.CommentLongClickHelper;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.KnowPraseData;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.ReportType;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 知识分享详情
 * <p>
 * Created by Administrator on 2017/9/11.
 */

public class KnowDetailActivity extends BaseActivity implements IKnowledgeDetailListener, IKnowGoodListener, IKnowledgeDelListener,
        KnowledgeHelper.IKnowledgeChangedListenr, IScoreReduceListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;
    //    private HtmlTextView htmlTextView;
    private KnowDetailManager manager;
    private int knowledgeId;
    private TextView mTitleTV;
    private TextView answerTV;
    private TextView praiseTV;
    private TextView forwardTV;
    private TextView deleteTV;
    private TextView visitorTV;
    private View answerLine;
    private View praiseLine;

    private ImageView headIV;
    private TextView nameTV;
    private ImageView sexIV;
    private ImageView addV;
    private TextView labelTV;
    private LinearLayout userLayout;

    private final String imageStart = "<img src=\"";
    private final String imageEnd = "\">";
    private KnowledgeData knowledgeData;
    private KnowGoodManager goodManger;
    private KnowDelManager delManager;
    private ScoreReduceManager scoreReduceManager;
    /**
     * 标题右边图片
     */
    private ImageButton rightImageBtn;
    private Dialog dialog;
    private LinearLayout conentLayout;
    private SpanTextView mSpanTextView;
    //    private LinearLayout scoreControlLayout;
    private TextView scoreCountTV;
    private Button readKnowBtn;
    private KnowledgeHelper knowledgeHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_know_detail, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        initWattingView();
        setTitleName(R.string.knowledge_detail);
        initView();
        getData();
        initData();
        knowledgeHelper = KnowledgeHelper.getInstance();
        knowledgeHelper.addListener(this);
    }

    private void initWattingView() {
        waittingLayout = (LinearLayout) findViewById(R.id.waitting_layout);
        waittingProBar = (ProgressBar) findViewById(R.id.waitting_progress);
        waittingTV = (TextView) findViewById(R.id.waitting_text_desc);
    }

    private void getData() {
        Intent intent = getIntent();
        String id = intent.getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            knowledgeId = Integer.valueOf(id);
        } else {
            knowledgeId = intent.getIntExtra(Const.INTENT_ID, 0);
        }
        knowledgeData = new KnowledgeData();
        knowledgeData.setId(knowledgeId);
    }

    private void initView() {
        rightImageBtn = (ImageButton) findViewById(R.id.right_imagebutton);
        rightImageBtn.setVisibility(View.VISIBLE);
        rightImageBtn.setImageResource(R.drawable.sandian);
        rightImageBtn.setOnClickListener(this);
        mTitleTV = (TextView) findViewById(R.id.know_detail_title);
        answerTV = (TextView) findViewById(R.id.include_answer_tv);
        praiseTV = (TextView) findViewById(R.id.include_praise_tv);
        forwardTV = (TextView) findViewById(R.id.include_forward_tv);
        deleteTV = (TextView) findViewById(R.id.include_delete_tv);
        visitorTV = (TextView) findViewById(R.id.include_visitor_tv);
        answerLine = (View) findViewById(R.id.include_answer_line);
        praiseLine = (View) findViewById(R.id.include_praise_line);
        headIV = (ImageView) findViewById(R.id.user_head);
        nameTV = (TextView) findViewById(R.id.user_name);
        labelTV = (TextView) findViewById(R.id.user_label);
        sexIV = (ImageView) findViewById(R.id.user_sex);
        addV = (ImageView) findViewById(R.id.add_v_iv);
        userLayout = (LinearLayout) findViewById(R.id.user_head_layout);
        conentLayout = (LinearLayout) findViewById(R.id.know_detail_contentLayout);
//        scoreControlLayout = (LinearLayout) findViewById(R.id.score_control_layout);
        scoreCountTV = (TextView) findViewById(R.id.score_count);
        readKnowBtn = (Button) findViewById(R.id.read_knowledge_btn);
        answerTV.setOnClickListener(this);
        praiseTV.setOnClickListener(this);
        forwardTV.setOnClickListener(this);
        deleteTV.setVisibility(View.INVISIBLE);
        deleteTV.setOnClickListener(this);
        userLayout.setOnClickListener(this);
        headIV.setOnClickListener(this);
        readKnowBtn.setOnClickListener(this);
    }

    private void initData() {
        manager = new KnowDetailManager(this);
        manager.addKnowledgeDetailListener(this);
        goodManger = new KnowGoodManager(this);
        goodManger.addKnowGoodListener(this);
        delManager = new KnowDelManager(this);
        delManager.addKnowledgeDelListener(this);
        scoreReduceManager = new ScoreReduceManager(this);
        scoreReduceManager.addScoreReduceListener(this);
        reqData();
    }

    private void reqData() {
        manager.knowledgeDetail(GlobalContext.getAccountId(), knowledgeId);
    }

    @Override
    public void onKnowledgeDetailFailure(int errorCode, String errorMsg) {
        if (errorCode == ErrorCode.KNOWLEDGE_ALEARY_DEL) {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
            knowledgeHelper.deleteNotify(knowledgeId);
        } else {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText("加载失败，请稍后再试...");
        }
    }

    @Override
    public void onKnowledgeDetailSuccess(KnowledgeData data) {
        waittingLayout.setVisibility(View.GONE);
        knowledgeData = data;
        if (null != data) {
            // 显示前 先清空content的内容
            conentLayout.removeAllViews();
            display(knowledgeData);
        }

    }

    private void display(KnowledgeData data) {
        if (data.getUserInfo().accountId == GlobalContext.getAccountId()) {
            rightImageBtn.setVisibility(View.GONE);
        }
        mTitleTV.setText(data.getSubject() == null ? "" : data.getSubject());
        PictureDownloadUtils.displayHeadImage(this, headIV, data.getUserInfo().headPic);
        nameTV.setText(data.getUserInfo().realName);
        labelTV.setText(data.getUserInfo().label);
        Utils.showSex(this, data.getUserInfo().sex, sexIV);
        Utils.showAuth(data.getUserInfo(), addV);
        Utils.showPriseCounts(data.getAnswerCount(), answerTV);
//            Utils.showPriseCounts(data.getForwardCount(), forwardTV);
        Utils.showVisitorCounts(data.getVisitorCount(), visitorTV);
        Utils.praiseChanged(this, data.getIsGood(), data.getGoodCount(), praiseTV);
        if (GlobalContext.getAccountId() == data.getUserInfo().accountId) {
            deleteTV.setVisibility(View.VISIBLE);
        }

        if (data.getStatus() == KnowledgeData.STATUS_INIT || data.getStatus() == KnowledgeData.STATUS_REFUSE) {
            // 屏蔽 回复，分享，删除按钮
            answerTV.setVisibility(View.INVISIBLE);
            answerLine.setVisibility(View.INVISIBLE);
            praiseTV.setVisibility(View.INVISIBLE);
            praiseLine.setVisibility(View.INVISIBLE);
            forwardTV.setVisibility(View.INVISIBLE);
        }

        GlobalUserData userData = new GlobalUserData();
        userData.setScore(data.getLookAccountScore());
//        GlobalContext.score = data.getLookAccountScore();
        ScoreChangeManager scoreChangeManager = ScoreChangeManager.getInstance();
        scoreChangeManager.updateScore();
        String my_score = String.format(getResources().getString(R.string.my_score_detail), data.getLookAccountScore() + "");
        scoreCountTV.setText(my_score);
        // 是否已经支付积分:0未支付，1已经支付
        if (0 == data.getIsScoreBuy() && data.getScore() > 0) {
            readKnowBtn.setVisibility(View.VISIBLE);
            scoreCountTV.setVisibility(View.VISIBLE);
            if (null != data.getUserInfo()) {
            }
            String reduce_score = String.format(getResources().getString(R.string.reduce_score), data.getScore() + "");
            readKnowBtn.setText(reduce_score);
        } else if (1 == data.getIsScoreBuy() || 0 == data.getScore()) {
            readKnowBtn.setVisibility(View.GONE);
            scoreCountTV.setVisibility(View.GONE);
        }

        String content = data.getContent();
        /**
         * 步骤：
         * 1。先把内容分隔成不同的List<KnowPraseData> 列表形式
         * 2。根据不同的内容，生成多个SpanTextView布局，分别封装该内容
         * 3。对于纯文本内容，做@处理
         * 4。回归调用完成，显示内容，并对内容做点击事件处理
         *
         */

        List<KnowPraseData> praseList = splitImageContentByImages(content, data.getNoticeJson());
        insertContent(praseList, 0);

//        Utils.showHtmlSpanContent(this, content, data.getNoticeJson(), htmlTextView);
//        List<FindClass> mContentList = splitImageContentByImages(content);
//        insertContent(mContentList,0,htmlTextView);

//        String str = getHtmlString(content);
//        str = "<font color='#057dff'>" + "@sanshao" + "</font>" + str;
//
//        htmlTextView.setHtmlFromString(str, false);
//        SpannableString spannableString = new SpannableString("@三少");
//        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#057dff")),0,3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
//        htmlTextView.setText(spannableString);

    }


    private String getHtmlString(String content) {
        Pattern p = Pattern.compile("\\{\"image\":[^}]*\\}");
        Matcher m = p.matcher(content);
        List<KnowImageData> resultList = new ArrayList<KnowImageData>();
        while (m.find()) {
            String tmp = m.group();
            KnowImageData imageData = JsonUtil.toObject(tmp, KnowImageData.class);
            imageData.content = tmp;
            imageData.type = 2;
            resultList.add(imageData);
        }
        for (int i = 0; i < resultList.size(); i++) {
            content = content.replace(resultList.get(i).content, imageStart + GlobalContext.cdndownUrl + resultList.get(i).image + imageEnd);
        }
        return content;
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.user_head:
            case R.id.user_head_layout:
                Utils.intoHeadInfoActivity(knowledgeData.getUserInfo().accountId, KnowDetailActivity.this);
                break;

            case R.id.include_answer_tv:
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                    return;
                }

                Intent intent = new Intent();
                intent.putExtra(Const.INTENT_ID, knowledgeId);
                intent.setClass(KnowDetailActivity.this, KnowAnswerActivity.class);
                startActivity(intent);
                break;
            case R.id.include_praise_tv:
                int goodCounts = knowledgeData.getGoodCount();
                if (0 == knowledgeData.getIsGood()) {
                    knowledgeData.setIsGood(1);
                    goodCounts++;
                } else {
                    knowledgeData.setIsGood(0);
                    goodCounts--;
                }
                knowledgeData.setGoodCount(goodCounts);
//                Utils.praiseChanged(this, knowledgeData.getIsGood(), knowledgeData.getGoodCount(), praiseTV);
                // 请求点赞接口
                goodManger.knowGood(GlobalContext.getAccountId(), knowledgeData.getId());
                // 通知界面改变点赞状态
                knowledgeHelper.goodNotify(knowledgeId, knowledgeData.getIsGood(), knowledgeData.getGoodCount());
                break;
            case R.id.include_forward_tv:
                String imageUrl = imageUrl = GlobalContext.cdndownUrl + "logo.png";
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(KnowDetailActivity.this, knowledgeData.getShortContent(), 8, imageUrl, knowledgeData.getId());
                break;
            case R.id.include_delete_tv:
                showDeleteDialog();
                break;
            case R.id.right_imagebutton:
                showDialog();
                break;
            case R.id.read_knowledge_btn:
                // 正在扣除积分等待框
                scoreReduceManager.scoreReduce(GlobalContext.getAccountId(), 6, knowledgeId);
                break;
            default:
                break;
        }
    }

    @Override
    public void onKnowGoodFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onKnowGoodSuccess() {

    }

    /**
     * 显示举报弹出框
     */
    private void showDialog() {
        CommentLongClickHelper.getInstance().showReportDialog(this, ReportType.TYPE_KNOW, knowledgeId);
    }


    /**
     * 显示删除弹出框
     */
    private void showDeleteDialog() {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("您确认要删除这篇文章吗？");
        builder.setPositiveButton(this.getResources().getString(R.string.confirm),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        delManager.knowledgeDel(GlobalContext.getAccountId(), knowledgeId);
                    }
                });
        builder.setNegativeButton(this.getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager)
            manager.removeKnowledgeDetailListener(this);
        if (null != goodManger)
            goodManger.removeKnowGoodListener(this);
        if (null != delManager)
            manager.removeKnowledgeDetailListener(this);
        if(null != knowledgeHelper){
            knowledgeHelper.removeListener(this);
        }
        if(null != scoreReduceManager){
            scoreReduceManager.removeScoreReduceListener(this);
        }

    }

    @Override
    public void onKnowledgeDelFailure(int errorCode, String errorMsg) {
        Notification.toast(this, errorMsg);
    }

    @Override
    public void onKnowledgeDelSuccess() {
        knowledgeHelper.deleteNotify(knowledgeId);
        this.finish();
    }

    @Override
    public void addOneKnowledge(KnowledgeData data) {

    }

    @Override
    public void removeOneKnowledge(int knowledgeId) {

    }

    @Override
    public void goodNotify(int knowledgeId, int isGood, int goodCount) {
        if (this.knowledgeId == knowledgeId) {
            knowledgeData.setIsGood(isGood);
            knowledgeData.setGoodCount(goodCount);
            Utils.praiseChanged(this, isGood, goodCount, praiseTV);
        }
    }

    @Override
    public void replyNotify(int knowledgeId, int answerCounts) {
        if (this.knowledgeId == knowledgeId) {
            knowledgeData.setAnswerCount(answerCounts);
            Utils.showPriseCounts(answerCounts, answerTV);
        }
    }

    @Override
    public void visitorNotify(int knowledgeId, int visitorCounts) {
        if (this.knowledgeId == knowledgeId) {
            knowledgeData.setVisitorCount(visitorCounts);
            Utils.showVisitorCounts(visitorCounts, visitorTV);
        }
    }

    @Override
    public void modifyOneData(int knowledgeId, KnowledgeData data) {

    }

    @Override
    public void onScoreReduceFailure(int errorCode, String errorMsg) {
        if (errorCode == ErrorCode.NO_SCORE) {
            ErrorDialogHelper.getInstance().showNoScore(this);
        } else {
            Notification.toast(this, errorMsg);
        }
    }

    @Override
    public void onScoreReduceSuccess() {
        reqData();
    }

    class FindClass {
        public int index;
        public String content;
    }

    private List<KnowPraseData> splitImageContentByImages(String content, String noticeJson) {
        List<KnowPraseData> mContentList = new ArrayList<>();
        Pattern p = Pattern.compile("\\{\"image\":[^}]*\\}");
        Matcher m = p.matcher(content);
        List<FindClass> resultList = new ArrayList<>();
        while (m.find()) {
            String tmp = m.group();
            FindClass find = new FindClass();
            find.index = content.indexOf(tmp);
            find.content = tmp;
            resultList.add(find);
        }

        int preIndex = 0;
        for (int i = 0; i < resultList.size(); i++) {
            FindClass find = resultList.get(i);
            String str = "";
            if (find.index > 0) {
                str = content.substring(preIndex, find.index);
//                mContentList.add(str);
                KnowPraseData praseData = new KnowPraseData();
                praseData.index = 0;
                praseData.type = 1;
                praseData.content = str;
                praseData.noticeJson = noticeJson;
                mContentList.add(praseData);
            }
            KnowPraseData data = new KnowPraseData();
            data.index = find.index;
            data.content = find.content;
            data.type = 2;
            data.noticeJson = null;
            mContentList.add(data);
            preIndex = find.index + find.content.length();
        }
        if (preIndex < content.length()) {
            KnowPraseData data = new KnowPraseData();
            data.type = 1;
            data.index = preIndex;
            data.content = content.substring(preIndex, content.length());
            data.noticeJson = noticeJson;
            mContentList.add(data);
        }
        return mContentList;
    }

    public void insertContent(final List<KnowPraseData> urls, final int index) {
        if (index >= urls.size()) {
            return;
        }
        final String url = urls.get(index).content;

        if (url.indexOf(PictureAndTextEditorView.mBitmapStart) != -1) {//判断是否是图片地址
            KnowImageData imageData = praseUrl(url);
            Glide.with(this)
                    .load(GlobalContext.cdndownUrl + imageData.image)
                    .asBitmap()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                            ImageView iv = new ImageView(KnowDetailActivity.this);
                            //  图片显示的宽度为控件的宽度减去左右间隙宽度，不减左右间隙会显示两张一样的图片
                            int d_width = conentLayout.getWidth() - conentLayout.getPaddingRight() - conentLayout.getPaddingLeft();
                            //  根据宽度，算出图片的等比高度
                            int d_height = d_width * bitmap.getHeight() / bitmap.getWidth();
                            bitmap = Bitmap.createScaledBitmap(bitmap, d_width, d_height, true);
//                            System.out.println("hhhh:" + bitmap.getHeight() + "/" + bitmap.getWidth());
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
                            lp.setMargins(0, 0, 0, 0);
//                            iv.setLayoutParams(lp);
                            iv.setImageBitmap(bitmap);
//                            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                            conentLayout.addView(iv);
                            iv.setOnClickListener(new PicViewListener(index, urls));
                            insertContent(urls, index + 1);
                        }
                    });

        } else {
            //插入文字
            mSpanTextView = new SpanTextView(this);
            mSpanTextView.setGravity(Gravity.CENTER_VERTICAL);
            mSpanTextView.setTextColor(getResources().getColor(R.color.black));
            mSpanTextView.setTextSize(14);
            mSpanTextView.setLineSpacing(DisplayUtils.dp2px(this, 6), 1);
            Utils.showSpanContent(this, urls.get(index).content, urls.get(index).noticeJson, mSpanTextView);
            conentLayout.addView(mSpanTextView);
            insertContent(urls, index + 1);
        }
    }

    private KnowImageData praseUrl(String url) {
        KnowImageData imageData = JsonUtil.toObject(url, KnowImageData.class);
        if (null == imageData) {
            return new KnowImageData();
        }
        imageData.content = url;
        imageData.type = 2;
        return imageData;
    }

    /**
     * 查看图片
     */
    class PicViewListener implements View.OnClickListener {

        private List<KnowPraseData> urls;
        private int index;

        public PicViewListener(int index, List<KnowPraseData> urls) {
            this.urls = urls;
            this.index = index;
        }

        @Override
        public void onClick(View view) {
            int position = 0;
            ArrayList<String> resultList = new ArrayList<>();
            for (int i = 0; i < urls.size(); i++) {
                if (index == i) {
                    position = resultList.size();
                }
                if (urls.get(i).type == 2) {
                    KnowImageData data = praseUrl(urls.get(i).content);
                    resultList.add(GlobalContext.cdndownUrl + data.image);
                }
            }
            // 查看图片详情
            Utils.imageBrower(KnowDetailActivity.this, position, resultList);
        }

        private List<String> getUrls(int index, List<KnowPraseData> list) {
            List<String> resultList = new ArrayList<>();
            for (KnowPraseData praseData : list) {
                if (praseData.type == 2) {
                    KnowImageData data = praseUrl(praseData.content);
                    resultList.add(data.image);
                }
            }
            return resultList;
        }

    }

}